<?php

namespace App\Http\Controllers\Web\Buyer;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\OrdersCrontab;
use App\Repository\Repositories\Interfaces\AttributeCrontabsRepository;
use App\Repository\Repositories\Interfaces\InvoicesRepository;
use App\Repository\Repositories\Interfaces\OrderProductsRepository;
use App\Repository\Repositories\Interfaces\OrderQualificationBidRepository;
use App\Repository\Repositories\Interfaces\OrderQualificationDetailRepository;
use App\Repository\Repositories\Interfaces\OrderQualificationRepository;
use App\Repository\Repositories\Interfaces\OrdersRepository;
use App\Repository\Repositories\Interfaces\UserInvoiceRepository;
use Illuminate\Http\Request;

/**
 * 资质订单管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class OrderQualificationBidController extends BaseController
{
    /**
     * @var OrdersRepository
     */
    protected $orders_repo;

    protected $user_id;
    protected $order;

    public function __construct(OrderQualificationRepository $orders_repo,OrdersRepository $order)
    {
        parent::__construct();
        $this->orders_repo = $orders_repo;
        $this->order = $order;
        $this->user_id = array_get($this->user, 'id');
    }

    /**
     * 资质订单创建
     */
    public function store(Request $request,UserInvoiceRepository $user_invoice_repo, InvoicesRepository $invoices_repo,
                          AttributeCrontabsRepository $orders_crontab_repo,OrderQualificationDetailRepository $order_detail,OrderProductsRepository $order_product)
    {
        $data=$request->all();

        //发票信息公共部分
        if(isset($data['invoices'])){
            $invoices = $user_invoice_repo->findWhereIn('id', array_unique($data['invoices']), [
                'id', 'invoice_message', 'invoice_type', 'invoice_title', 'tax_code', 'invoice_address',
                'invoice_tel', 'invoice_bank', 'invoice_account', 'post_address', 'post_contacts', 'post_tel'
            ]);
            //为店铺分配发票
            foreach($invoices['data'] as $invoice){
                array_walk($data['invoices'], function(&$value, $key) use ($invoice){
                    $value = $value == $invoice['id'] ? $invoice : null;
                });
            }
        }else{
            $invoices = [];
        }
        \DB::beginTransaction();
        try {

            //生成资质订单
            $data2=$request->all(['shop_id','bid_date','project_name','project_inf','remark','appendix']);
            $data2['user_id']=$this->user_id;
            $order = $this->orders_repo->create($data2);

            //订单金额计算
            $price=0;
            foreach($data['attri'] as $k=>$v){
                $price+=$v['price'];
            }
            //生成订单
            $order_data=[
                'order_type'=>6,
                'shop_id'=>$data2['shop_id'],
                'user_id'=>$this->user_id,
                'remark'=>$data2['remark'],
                'initial_product_money'=>$price,
                'product_money'=>$price,
                'order_money'=>$price,
                'freight'=>0.00,//实际运费
                'is_claim_invoice'=>isset($invoices)?1:0,//是否索取发票 0不索取  1索取
            ];
            $order_arr=$this->order->create($order_data);

            $this->orders_repo->update(['order_code'=>$order_arr['data']['order_code']],$order['data']['id']);
            $service_code = $order_arr['data']['order_code'];
            //生成订单产品

            $result=[
                'shop_name'=>$data['shop_name'],
                'order_code'=>$service_code,
                'total_money'=>$price,
            ];
            foreach($data['attri'] as $k=>$v){
                $attr_data=[
                    'shop_id'=>$data2['shop_id'],
                    'shop_name'=>$data['shop_name'],
                    'user_id'=>$this->user_id,
                    'product_id'=>$v['product_id'],
                    'product_price'=>$v['price'],//产品单价
                    'product_name'=>$v['product_name'],
                    'order_code'=>$order_arr['data']['order_code'],
                    'quantity'=>1,//产品数量
                    'product_money'=>$v['price'],//产品总价
                    'product_img_url'=>$v['product_img_url'],
                    'attributes'=>$v['attributes'],
                ];
                $order_product->create($attr_data);
            }

            //生成订单自动取消记录
            $order_time = 3600*24*7;
            $orders_crontab_cancel_data = [
                'expired_at' => date('Y-m-d H:i:s', time() + $order_time),
                'order_id' => $order['data']['id'],
                'type' => OrdersCrontab::TYPE_CANCEL
            ];
            $orders_crontab_repo->create($orders_crontab_cancel_data);

            //生成订单自动确认记录
            $receipt_time =  3600*24*90;
            $orders_crontab_affirm_data = [
                'expired_at' => date('Y-m-d H:i:s', time() + $receipt_time),
                'order_id' => $order['data']['id'],
                'type' => OrdersCrontab::TYPE_AFFIRM
            ];
            $orders_crontab_repo->create($orders_crontab_affirm_data);

            //发票创建

            if(!empty($invoices)){
                $data['invoices'][$data['shop_id']]['invoice_price'] = $price;
                $data['invoices'][$data['shop_id']]['user_id'] = $this->user_id;
                $data['invoices'][$data['shop_id']]['order_code'] = $order_arr['data']['order_code'];

                $invoice_id=$invoices_repo->create($data['invoices'][$data['shop_id']]);
                $update=[
                    'invoce_id'=>$invoice_id['data']['id']
                ];
                $this->orders_repo->update($update,$order['data']['id']);
            }

            $ret = true;
            \DB::commit();
        } catch (\Exception $e) {
            throw  new \Exception($e);
            \DB::rollback(); //事务回滚;
            $ret = false;
        }

        if($ret){
            return $this->success(ErrorConst::SUCCESS_CODE_MSG, ['data' => $result]);
        }else{
            return $this->error(ErrorConst::FAILED_CODE_MSG, ErrorConst::FAILED_CODE);
        }
    }
    
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'q_status' => 'required|in:1,2,3,4,5,6,7',
        ]);
        
        $data = $request->all(['q_status']);
        $data['status']=$data['q_status'];
        
        $this->orders_repo->scopeQuery(function ($query){
            return $query->where(['user_id' => $this->user_id]);
        });
        
        $ret = $this->orders_repo->update($data, $id);
        
        return $this->noDataReturn($ret);
    }

}
